package api

import (
	"github.com/gin-gonic/gin"
	"go-mall/app/client/dto"
	"go-mall/app/client/model"
	"go-mall/global"
	"go-mall/global/request"
	"go-mall/global/response"
	"go-mall/pkg/jwt"
	"go.uber.org/zap"
	"time"
)

type UserApi struct{}

// Register 注册api
func (api *UserApi) Register(c *gin.Context) {
	var u dto.RegisterReq
	err := c.ShouldBindJSON(&u)
	if err != nil {
		response.FailMsg(err.Error(), c)
		return
	}
	defaultBirthday := time.Date(2000, 10, 01, 15, 00, 00, 00, time.Local) // 返回时间格式Time
	user := &model.User{Email: u.Email, Password: u.Password, Sex: u.Sex, Birthday: defaultBirthday}
	userResult, err := userService.Register(*user, u.Code)
	if err != nil {
		global.LOG.Error("注册失败！", zap.Error(err))
		response.FailData(err.Error(), "注册失败", c)
		return
	}
	response.OkData(userResult, "注册成功", c)
}

// Login 登陆api
func (api *UserApi) Login(c *gin.Context) {
	var l dto.LoginReq
	err := c.ShouldBind(&l)
	if err != nil {
		response.FailMsg(err.Error(), c)
		return
	}
	u := &model.User{Email: l.Email, Password: l.Password}
	user, err := userService.Login(*u, l.Code)
	if err != nil {
		//global.LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Error(err))
		//response.FailMsg("用户名不存在或者密码错误", c)
		global.LOG.Error("登陆失败!", zap.Error(err))
		response.FailData(err.Error(), "登录失败", c)
		return
	}
	//token := "token"
	//response.OkData(userVO.Login(*user, token), "登录成功", c)
	// 签发token
	api.generateToken(c, *user)
}

// generateToken 登录以后签发jwt
func (api *UserApi) generateToken(c *gin.Context, user model.User) {
	j := jwt.JWT{SigningKey: []byte(global.CONFIG.JWT.SigningKey)} // 唯一签名
	claims := j.CreateClaims(request.BaseClaims{
		ID:       user.ID,
		NickName: user.NickName,
		Username: user.UserName,
	})
	token, err := j.CreateToken(claims)
	if err != nil {
		global.LOG.Error("生成token失败！", zap.Error(err))
		response.FailMsg("成功token失败！", c)
		return
	}

	if !global.CONFIG.System.UseMultipoint {
		expiresAt := claims.RegisteredClaims.ExpiresAt.Format("2006-01-02 15:04:05")
		response.OkData(userVO.Login(user, token, expiresAt), "登录成功", c)
	}

}

// SendEmail 发送邮箱验证码
func (api *UserApi) SendEmail(c *gin.Context) {
	var e dto.EmailReq
	err := c.ShouldBind(&e)
	if err != nil {
		response.FailMsg(err.Error(), c)
		return
	}
	err = userService.SendEmail(e)
	if err != nil {
		response.FailMsg(err.Error(), c)
		return
	}
	response.OkMeg("发送邮箱验证码成功", c)
}

// Logout 退出登录
func (api *UserApi) Logout(c *gin.Context) {

}

// GetUser 获取用户信息
func (api *UserApi) GetUser(c *gin.Context) {
	response.FailMsg("测试获取用户信息", c)
}

// SetUser 修改用户信息
func (api *UserApi) SetUser(c *gin.Context) {
	response.FailMsg("修改用户信息", c)
}

// ChangePassword 修改用户密码
func (api *UserApi) ChangePassword(c *gin.Context) {

}

// ResetPassword 重置用户密码
func (api *UserApi) ResetPassword(c *gin.Context) {

}
